using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using VotingSystem.Data;
using VotingSystem.Models;
using Microsoft.AspNetCore.Http.Features;
using VotingSystem.Services;

var builder = WebApplication.CreateBuilder(args);

// 配置 Kestrel 服务器使用特定端口
builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.ListenLocalhost(5144); // HTTP
    serverOptions.ListenLocalhost(7144, listenOptions =>
    {
        listenOptions.UseHttps();
    }); // HTTPS
});

// Add services to the container.
builder.Services.AddControllersWithViews();

// 添加数据库上下文
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));

// 添加身份服务
builder.Services.AddDefaultIdentity<ApplicationUser>(options => 
{
    options.SignIn.RequireConfirmedAccount = false;  // 禁用账户确认要求
    options.Password.RequireDigit = false;           // 不要求包含数字
    options.Password.RequireLowercase = false;       // 不要求包含小写字母
    options.Password.RequireUppercase = false;       // 不要求包含大写字母
    options.Password.RequireNonAlphanumeric = false; // 不要求包含特殊字符
    options.Password.RequiredLength = 3;             // 最小长度为3
})
.AddEntityFrameworkStores<ApplicationDbContext>();

// 配置Cookie策略
builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Account/Login";
    options.LogoutPath = "/Account/Logout";
    options.AccessDeniedPath = "/Account/AccessDenied";
    options.ExpireTimeSpan = TimeSpan.FromDays(7);   // Cookie 过期时间
    options.SlidingExpiration = true;                // 启用滑动过期
});

// 配置文件上传限制
builder.Services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 10 * 1024 * 1024; // 10MB
});

builder.Services.AddScoped<PdfExportService>();
builder.Services.AddScoped<ExcelExportService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
